﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebNet.Extensions
{
    public static class StringExtentions
    {
        public static string JoinStringItem(this String str, string splitter, List<string> list)
        {
            StringBuilder sbStr = new StringBuilder();
            list.ForEach(o =>
            {
                sbStr.AppendFormat("'{0}'", o).Append(splitter);
            });

            if (sbStr.Length > 0)
            {
                sbStr.Remove(sbStr.Length - splitter.Length, splitter.Length);
            }

            return sbStr.ToString();
        }

        public static string Truncate(this String str, int length)
        {
            string text = str.Trim();
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            byte[] data = Encoding.Default.GetBytes(text);
            if (data.Length > length)
            { 
                byte[] newData = new byte[length];
                Array.Copy(data, newData, length);
                text = Encoding.Default.GetString(newData);
                int lastIndex = text.LastIndexOf("?");
                if (lastIndex != -1)
                {
                    text = text.Substring(0, lastIndex);    //remove last ? unknow ascii
                }
            }

            return text;
        }
    }
}
